package com.ccteam.shared.domain.playlistsheet

import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import androidx.paging.map
import com.ccteam.shared.api.UserDataSource
import com.ccteam.shared.core.UserCore
import com.ccteam.shared.data.playlistsheet.PlaylistSheetUserPagingSource
import com.ccteam.shared.domain.PagingUseCase
import com.ccteam.shared.result.playlistsheet.PlaylistSheetListItem
import com.ccteam.shared.utils.EMPTY_STRING
import com.ccteam.shared.utils.PHOTO_QUALITY
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import javax.inject.Inject

/**
 * @author Xiaoc
 * @since 2021/3/21
 *
 * 获取用户自己的歌单列表内容Domain层
 */
class PlaylistSheetListUserDataUseCase @Inject constructor(
    private val userCore: UserCore,
    private val userDataSource: UserDataSource,
): PagingUseCase<String, PlaylistSheetListItem>(
    Dispatchers.IO
) {

    override fun execute(parameters: String): Flow<PagingData<PlaylistSheetListItem>> {
        val userInfo = userCore.userInfo.value
        val isLogin = userCore.isLogin.value

        if(!isLogin ||
            userInfo.userToken.isNullOrEmpty()
            || userInfo.userId.isNullOrEmpty()){
            return flowOf(PagingData.empty())
        }
        return Pager(
            PagingConfig(pageSize = 15,initialLoadSize = 15)
        ){
            PlaylistSheetUserPagingSource(userInfo.userToken,parameters,userDataSource)
        }.flow.map { pagingData ->
            // 将分页数据转换成 PlaylistSheetListItem
            pagingData.map {
                PlaylistSheetListItem(
                    it.id,it.playlistName,it.imgUrl + PHOTO_QUALITY
                )
            }
        }
    }
}